package com.travel.api;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.travel.service.PdfService;
import com.travel.service.UserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

/**
 * @author chendikai
 * @description 生成pdf和下载pdf
 * @date 2024-07-09 17:31
 */
@RestController
@RequestMapping("/api/pdf")
@Api(tags = "pdf下载和查看")
public class PdfController {


    @Autowired
    @Qualifier("pdfTemplateServiceImpl")
    private PdfService pdfService;

    @GetMapping("/download/{orderId}")
    @ApiOperation("pdf下载")
    @ApiImplicitParam(name = "orderId", value = "订单id")
    public void download(HttpServletResponse response,@PathVariable String orderId) {
        try {

            response.reset();
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition",
                    "attachment;filename=user_pdf_" + System.currentTimeMillis() + ".pdf");

            OutputStream os = response.getOutputStream();
            pdfService.generateItextPdfDocument(os, orderId);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("pdf转换成图片查看")
    @ApiImplicitParam(name = "orderId", value = "订单id")
    @GetMapping("/longimage/{orderId}")
    public void getPdfAsLongImage(HttpServletResponse response, @PathVariable String orderId) throws Exception {
//        byte[] imageBytes = pdfService.generatePdfAndConvertToLongImage(userId);
//        response.setContentType("image/png");
//        response.setContentLength(imageBytes.length);
//        String base= Base64.getEncoder().encodeToString(imageBytes);
//        response.getWriter().write(base);

        byte[] imageBytes = pdfService.generatePdfAndConvertToLongImage(orderId);
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        // 如果只是返回Base64字符串，可以设置为text/plain
        // 如果将Base64字符串嵌入到JSON中，则设置为application/json
        response.setContentType("text/plain");
        // 写入Base64字符串到响应
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(base64Image);
    }
}
